package com.yuzhi.master.drainMsgNotice.controller;

import java.util.List;
import java.util.Arrays;
import java.util.Map;

import com.yuzhi.common.core.controller.BaseController;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.helper.LoginHelper;
import com.yuzhi.master.pump.service.IDrainPumpBjService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.yuzhi.common.core.domain.ApiResult;
import com.yuzhi.master.drainMsgNotice.domain.vo.DrainMsgNoticeVo;
import com.yuzhi.master.drainMsgNotice.domain.bo.DrainMsgNoticeBo;
import com.yuzhi.master.drainMsgNotice.domain.request.DrainMsgNoticeReq;
import com.yuzhi.master.drainMsgNotice.service.IDrainMsgNoticeService;
import com.yuzhi.common.util.poi.ExcelUtil;

/**
 * 消息通知
 *
 * @author coding123
 * @date 2025-08-20
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/drainMsgNotice")
public class DrainMsgNoticeController extends BaseController {

    private final IDrainMsgNoticeService idrainMsgNoticeService;

    private final IDrainPumpBjService drainPumpBjService;

    /**
     * 查询消息通知列表
     */
    @SaCheckPermission("system:drainMsgNotice:list")
    @PostMapping("/list")
    public ApiResult<PageDataInfo> list(@RequestBody DrainMsgNoticeReq request) {
        return ApiResult.ok(idrainMsgNoticeService.queryPageList(request));
    }

    /**
     * 导出消息通知列表
     */
    @SaCheckPermission("system:drainMsgNotice:export")
    @PostMapping("/export")
    public void export(DrainMsgNoticeReq request, HttpServletResponse response) {
        List<DrainMsgNoticeVo> list = idrainMsgNoticeService.queryList(request);
        ExcelUtil.exportExcel(list, "消息通知", DrainMsgNoticeVo.class, response);
    }

    /**
     * 获取消息通知详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:drainMsgNotice:query")
    @GetMapping("/getInfoById/{id}")
    public ApiResult<DrainMsgNoticeVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String id) {
        return ApiResult.ok(idrainMsgNoticeService.queryById(id));
    }

    /**
     * 新增消息通知
     */
    @SaCheckPermission("system:drainMsgNotice:add")
    @PostMapping("/add")
    public ApiResult<Void> add(@Validated @RequestBody DrainMsgNoticeBo bo) {
        return toAjax(idrainMsgNoticeService.insertByBo(bo));
    }

    /**
     * 修改消息通知
     */
    @SaCheckPermission("system:drainMsgNotice:edit")
    @PostMapping("/edit")
    public ApiResult<Void> edit(@Validated @RequestBody DrainMsgNoticeBo bo) {
        return toAjax(idrainMsgNoticeService.updateByBo(bo));
    }

    /**
     * 删除消息通知
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:drainMsgNotice:remove")
    @DeleteMapping("/removeBatchById/{ids}")
    public ApiResult<Void> removeBatchById(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(idrainMsgNoticeService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 删除消息通知
     *
     * @param id 主键
     */
    @SaCheckPermission("system:drainMsgNotice:remove")
    @DeleteMapping("/removeById/{id}")
    public ApiResult<Void> removeById(@NotEmpty(message = "主键不能为空")
                                  @PathVariable String id) {
        return toAjax(idrainMsgNoticeService.deleteById(id, true));
    }

    /**
     * 移动端取每种消息类型最新的一条
     * @return
     */
    @GetMapping("/getAppLastMsgNotice")
    public ApiResult<List<DrainMsgNoticeVo>> getAppLastMsgNotice() {
        List<DrainMsgNoticeVo> voList  = idrainMsgNoticeService.getAppLastMsgNotice();
        return ApiResult.ok(voList);
    }

    /**
     * 修改消息通知状态
     * @param id 消息ID
     * @param status 通知状态(0-未读  1-已读)
     * @return
     */
    @GetMapping("/updateNoticeStatusById")
    public ApiResult<Void> updateNoticeStatusById(String id,String status ) {
        return toAjax(idrainMsgNoticeService.updateNoticeStatusById(id, status));
    }

    /**
     * 根据消息类型设置消息状态
     * 通知状态(0-未读  1-已读)
     * @param fkType
     * @param status
     * @return
     */
    @GetMapping("/updateStatusByFkType")
    public ApiResult<Void> updateStatusByFkType(String fkType,String status ) {
        return toAjax(idrainMsgNoticeService.updateStatusByFkType(fkType, status));
    }

    /**
     * APP我的未读消息数
     * @return
     */
    @GetMapping("/getAppMyUnreadMsg")
    public ApiResult<Integer> getAppMyUnreadMsg() {

        //获取当前登录的用户ID
        String userId = LoginHelper.getUserId();
        DrainMsgNoticeReq  request  = new DrainMsgNoticeReq();
        request.setNoticeUser(userId);
        request.setNoticeStatus("0");  //读取状态(0-未读  1-已读)

        List<DrainMsgNoticeVo>  list  =  idrainMsgNoticeService.queryList( request);

        return  ApiResult.ok(list.size());
    }



    /**
     * 测试接口: 调用 monitoringAnalysis 解析并入库
     * 请求示例:
     * {
     *   "deviceSn": "1810130046pump002",
     *   "decodedResponse": "{...完整JSON字符串...}"
     * }
     */
    @PostMapping("/monitoring/{deviceSn}")
    public ApiResult<Void> monitoring(@PathVariable String deviceSn, @RequestBody Map<String, Object> body) {
        if (deviceSn == null || deviceSn.isEmpty() || body == null) {
            return ApiResult.fail("参数错误: 需要 path 参数 deviceSn 与 JSON 请求体");
        }
        try {
            // 直接将请求体转回字符串传给解析方法
            String decodedResponse = com.alibaba.fastjson.JSONObject.toJSONString(body);
            drainPumpBjService.monitoringAnalysis(deviceSn, decodedResponse);
            return ApiResult.ok();
        } catch (Exception e) {
            log.error("测试监测数据解析失败 deviceSn={}, error={}", deviceSn, e.getMessage(), e);
            return ApiResult.fail("解析失败: " + e.getMessage());
        }
    }

}
